package com.lry.basic.thread;

import java.util.concurrent.Semaphore;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2020/1/7
 */
public class H2O1 {
    static int num = 10;
    static int index = 1;
    static int e=0;
    static Semaphore h = new Semaphore(2);
    static Semaphore o = new Semaphore(0);

    public static void main(String[] args) {
        H h = new H();
        O o = new O();
        Thread t1 = new Thread(h);
        Thread t2 = new Thread(o);
        t1.start();
        t2.start();
    }

    static class H implements Runnable{
        @Override
        public void run() {
            while(index<=num){
                try {
                    h.acquire();
                    if(index>num)break;
                    System.out.print("H");
                    e++;
                    if(e==2){
                        e=0;
                        o.release();
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    static class O implements Runnable{
        @Override
        public void run(){
            while(index<=num){
                try {
                    o.acquire();
                    System.out.print("O");
                    index++;
                    h.release(2);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }

            }
        }
    }

}
